package com.module.pubpage.ui.imagePager

import android.Manifest
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.common.app.core.RouterHub
import com.common.app.utls.HeadTitleUtils
import com.common.base.app.activity.BaseNavActivity
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.*
import com.common.base.utils.BitmapUtils.saveImageToGallery
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.module.pubpage.R
import com.module.pubpage.databinding.PubpageActivityImageDetailPageBinding
import java.io.File

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：7/2/2023
 *
 * 描述：查看大图
 *
 * 修订历史：
 *
 */
@Route(path = RouterHub.ROUTER_PUBPAGE_IMAGE_PAGE)
class ImagePagerActivity :
    BaseNavActivity<PubpageActivityImageDetailPageBinding>(),
    View.OnClickListener {

    @Autowired(name = "pagerPosition")
    @JvmField
    var pagerPosition = 0

    @Autowired(name = "images")
    @JvmField
    var imagePath = ArrayList<String>()

    var imgUrl: String? = ""

    var imagePathUrl = ArrayList<String>()

    override fun getViewContentBinding() =
        PubpageActivityImageDetailPageBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, false)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle("")
        headTitleUtils.setLineStyle(4)

        mViewContentBinding.vpPager.pageMargin = (resources.displayMetrics.density * 15).toInt()

        mViewContentBinding.ivBack.setOnClickListener({ view: View? -> finish() })
    }

    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.vpPager.setOnPageChangeListener(object :
            ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                mViewContentBinding.tvIndicator.text =
                    (position + 1).toString() + "/" + imagePath.size
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    override fun lazyInitData() {
        super.lazyInitData()

        imagePath.isNullOrEmpty().no {

            mViewContentBinding.tvIndicator.text =
                (pagerPosition + 1).toString() + "/" + imagePath.size

            mViewContentBinding.vpPager.adapter = object : PagerAdapter() {
                override fun isViewFromObject(view: View, `object`: Any): Boolean {
                    return view === `object`
                }

                override fun getCount(): Int {
                    return imagePath.size
                }

                override fun instantiateItem(container: ViewGroup, position: Int): Any {
//                    return super.instantiateItem(container, position)
                    val view = SubsamplingScaleImageView(this@ImagePagerActivity)
                    //使用Glide下载图片,保存到本地
                    Glide.with(this@ImagePagerActivity)
                        .download(imagePath[position])
                        .into(object : SimpleTarget<File?>() {
                            override fun onLoadFailed(errorDrawable: Drawable?) {
                                super.onLoadFailed(errorDrawable)
                            }

                            override fun onResourceReady(
                                resource: File,
                                transition: Transition<in File?>?
                            ) {
                                view.setImage(ImageSource.uri(resource.absolutePath))
                                imagePathUrl.add(resource.absolutePath.toString())
                                view.setTag(R.id.keyId, resource.absolutePath.toString())
//                                container.tag = resource.absolutePath.toString()
                                view.maxScale = 10f
                            }

                        })
                    view.setOnClickListener(View.OnClickListener { view ->
                        //防止多次点击
                        if (ViewUtils.isFastClick()) return@OnClickListener
                        finish()
                    })

                    view.setOnLongClickListener {
                        it.getTag(R.id.keyId).toString().isNullOrEmpty().no {
                            imgUrl = it.getTag(R.id.keyId).toString()
                            showAlertDialogTwoBtn(
                                getString(R.string.cancel_btn_zh),
                                getString(R.string.ok_btn_zh2),
                                "提示",
                                "是否保存本图片？"
                            )
                        }
                        false
                    }
                    container.addView(view)
                    return view
                }

                override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//                    super.destroyItem(container, position, `object`)
                    container.removeView(`object` as View)
                }
            }
            mViewContentBinding.vpPager.currentItem = pagerPosition
        }
    }

    override fun onClick(v: View?) {
        //防止多次点击
        if (ViewUtils.isFastClick()) return

    }

    override fun onTwoButtonOKClick() {
        super.onTwoButtonOKClick()
        RxPermissionHelper.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE).yes {
            toSaveImage()
        }.otherwise {
            RxPermissionHelper.request(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                if (it) {
                    toSaveImage()
                } else {
                    ToastUtils.showToast("存储权限被拒绝！")
                }
            }
        }
    }

    private fun toSaveImage(){
        imgUrl?.let {
            showDialogLoading()
            saveImageToGallery(it, this)
            dismissLoadingDialog()
        }
    }
}